<template>
    <div>微信登录</div>
</template>
<script>
import axios from "axios"
import authApi from "~/utils/auth"
//https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
const APPID = "wx3bdb1192c22883f3"
const SECRET = "db9d6b88821df403e5ff11742e799105"
export default {
    asyncData(context){
        let CODE = context.query.code
        let url1 = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${APPID}&secret=${SECRET}&code=${CODE}&grant_type=authorization_code`
        //发送http请求
        return axios.get(url1).then(res => {
            let ACCESS_TOKEN = res.data.access_token
            let OPENID = res.data.openid
            let url2 = `https://api.weixin.qq.com/sns/userinfo?access_token=${ACCESS_TOKEN}&openid=${OPENID}`
            return axios.get(url2).then(res1 => {
                console.log(res1.data.nickname)
                console.log(res1.data.headimgurl)
                return {
                    name: res1.data.nickname,
                    avatar: res1.data.headimgurl
                }
            })
        })
    },
    //当用户登录成功之后,页面渲染成功之后调用
    mounted(){
        authApi.setUser(this.name, "xxxx", this.avatar);
        location.href="/"
    }
}
</script>